package com.hzdesk.media.matvector.koreabatch.client.my_paperless.custom_view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.widget.ImageView;

import com.hzdesk.media.matvector.koreabatch.client.my_paperless.R;

/**
 * Created by Administrator on 2018/8/9.
 * 杭州席媒科技有限公司  Developers  刘传华  10
 * 佛祖镇楼 bug辟易
 *
 * 自定义的圆角矩形ImageView，可以直接当组件在布局中使用。
 */

@SuppressLint("AppCompatCustomView")
public class MyRoundRectImageView  extends ImageView {
    private Paint paint;
    private int round_px;
    public MyRoundRectImageView(Context context) {
        this(context,null);
    }

    public MyRoundRectImageView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
    }

    public MyRoundRectImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray array=context.obtainStyledAttributes(attrs, R.styleable.my_round_rect_view);
        round_px=array.getInt(R.styleable.my_round_rect_view_round_px,10);
        array.recycle();
        init();
    }

    private void init() {
        paint  = new Paint();

    }

    @Override
    protected void onDraw(Canvas canvas) {
        Drawable drawable = getDrawable();
        if(drawable != null){
            Bitmap bitmap =((BitmapDrawable) drawable).getBitmap();
            Bitmap b = getRoundBitmap(bitmap, round_px);
            final Rect rectSrc = new Rect(0, 0, b.getWidth(), b.getHeight());
            final Rect rectDest = new Rect(0,0,getWidth(),getHeight());
            paint.reset();
            canvas.drawBitmap(b, rectSrc, rectDest, paint);
        }else{
            super.onDraw(canvas);
        }
    }
    /**
     * @desc 获取圆角矩形图片方法
     *
     * @param bitmap
     * @param roundPx  一般设置成14
     * */
    private Bitmap getRoundBitmap(Bitmap bitmap, int roundPx) {
        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),bitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas =   new Canvas(output);
        int color = 0xff424242;
        Rect rect = new Rect(0,0,bitmap.getWidth(),bitmap.getHeight());
        RectF rectF =  new RectF(rect);
        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        int x = bitmap.getWidth();

        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);
        return output;
    }
}
